package com.yupi.springbootinit.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.model.dto.production.ProductionTaskClaimRequest;
import com.yupi.springbootinit.model.dto.production.printingrecord.*;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.vo.WorkflowTaskVO;
import com.yupi.springbootinit.model.vo.production.*;
import com.yupi.springbootinit.service.ProductionExecutionService;
import com.yupi.springbootinit.service.UserService;
import com.yupi.springbootinit.service.production.ProductionCardQueryService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**

 生产部（SC001）专属接口
 */
@Slf4j
@RestController
@RequestMapping("/production")
public class ProductionController {

    @Resource
    private ProductionCardQueryService productionCardQueryService;

    @Resource
    private ProductionExecutionService productionExecutionService;

    @Resource
    private UserService userService;

// ==================== 任务查询接口 ====================

    /**

     我的生产任务卡片（分页）
     */
    @GetMapping("/my/cards")
    public Page<ProductionTaskCardVO> getMyCards(
            @RequestParam(name = "pageNum", defaultValue = "1") long pageNum,
            @RequestParam(name = "pageSize", defaultValue = "10") long pageSize,
            @RequestParam(name = "userId", required = false) Long userIdOpt,
            @RequestParam(name = "departmentId", required = false) Long departmentIdOpt,
            @RequestParam(name = "departmentCode", required = false) String departmentCodeOpt,
            HttpServletRequest request
    ) {
        Long userId = userIdOpt;
        Long departmentId = departmentIdOpt;
        String departmentCode = departmentCodeOpt;

// 兜底：尝试从会话中读取
        try {
            Object uid = request.getSession().getAttribute("userId");
            if (userId == null && uid instanceof Long) userId = (Long) uid;
            Object did = request.getSession().getAttribute("departmentId");
            if (departmentId == null && did instanceof Long) departmentId = (Long) did;
            Object dcode = request.getSession().getAttribute("departmentCode");
            if (departmentCode == null && dcode instanceof String) departmentCode = (String) dcode;
        } catch (Exception ignored) {}

// 部门编码校验（若提供）
        if (departmentCode != null && !"SC001".equalsIgnoreCase(departmentCode)) {
            return new Page<>(pageNum, pageSize, 0);
        }

        return productionCardQueryService.pageMyProductionCards(userId, departmentId, departmentCode, pageNum, pageSize);
    }

    /**

     分页查询可认领的生产任务
     支持：
     status=ALL 返回全部状态
     includeProgress=true 批量附加“进度摘要”（清机 + 当前/下一工序）
     */
    @GetMapping("/tasks/available")
    public BaseResponse<Page<WorkflowTaskVO>> getAvailableTasks(
            @RequestParam(name = "status", required = false) String status,
            @RequestParam(name = "current", defaultValue = "1") long current,
            @RequestParam(name = "size", defaultValue = "20") long size,
            @RequestParam(name = "includeProgress", defaultValue = "false") boolean includeProgress,
            HttpServletRequest request
    ) {
        User loginUser = userService.getLoginUser(request);
        Page<WorkflowTaskVO> page = productionExecutionService.pageAvailableTasks(
                loginUser.getId(),
                status,
                current,
                size
        );
        if (includeProgress && page != null && page.getRecords() != null && !page.getRecords().isEmpty()) {
            productionExecutionService.attachProgressSummary(page.getRecords());
        }
        return ResultUtils.success(page);
    }
    /**

     分页查询我的生产任务
     */
    @GetMapping("/tasks/my")
    public BaseResponse<Page<WorkflowTaskVO>> getMyTasks(
            @RequestParam(name = "status", required = false) String status,
            @RequestParam(name = "current", defaultValue = "1") long current,
            @RequestParam(name = "size", defaultValue = "20") long size,
            HttpServletRequest request
    ) {
        User loginUser = userService.getLoginUser(request);
        Page<WorkflowTaskVO> page = productionExecutionService.pageMyProductionTasks(
                loginUser.getId(),
                status,
                current,
                size
        );
        return ResultUtils.success(page);
    }
    /**

     获取任务详情
     */
    @GetMapping("/tasks/{taskId}/detail")
    public BaseResponse<WorkflowTaskVO> getTaskDetail(@PathVariable("taskId") Long taskId) {
        WorkflowTaskVO taskVO = productionExecutionService.getTaskDetail(taskId);
        return ResultUtils.success(taskVO);
    }

    /**
     * 轻量获取PMC在批次上配置的粉末/清机设备信息
     */
    @GetMapping("/tasks/{taskId}/pmc-setup")
    public BaseResponse<com.yupi.springbootinit.model.vo.production.PmcSetupVO> getPmcSetup(@PathVariable("taskId") Long taskId) {
        com.yupi.springbootinit.model.vo.production.PmcSetupVO vo = productionExecutionService.getPmcSetup(taskId);
        return ResultUtils.success(vo);
    }
    /**
     * 获取生产任务详情（包含批次信息、产品列表、工序列表）
     */
    @GetMapping("/tasks/{taskId}/production-detail")
    public BaseResponse<ProductionTaskDetailVO> getProductionTaskDetail(@PathVariable("taskId") Long taskId) {
        ProductionTaskDetailVO detail = productionExecutionService.getProductionTaskDetail(taskId);
        return ResultUtils.success(detail);
    }
    /**

     获取任务统计（按状态分组）

     scope=dept 返回全部门统计
     scope=me（默认）返回个人统计（userId 未传时取当前登录人）
     */
    @GetMapping("/tasks/statistics")
    public BaseResponse<Map<String, Long>> getTaskStatistics(
            @RequestParam(name = "scope", defaultValue = "me") String scope,
            @RequestParam(name = "userId", required = false) Long userId,
            HttpServletRequest request
    ) {
        if ("dept".equalsIgnoreCase(scope)) {
            Map<String, Long> statistics = productionExecutionService.getTaskStatistics(null);
            return ResultUtils.success(statistics);
        }
        if (userId == null) {
            try {
                User loginUser = userService.getLoginUser(request);
                userId = loginUser.getId();
            } catch (Exception e) {
                log.debug("获取登录用户失败，将返回空统计", e);
                return ResultUtils.success(new java.util.HashMap<>());
            }
        }
        Map<String, Long> statistics = productionExecutionService.getTaskStatistics(userId);
        return ResultUtils.success(statistics);
    }

// ==================== 任务操作接口 ====================

    /**

     认领任务
     */
    @PostMapping("/tasks/claim")
    public BaseResponse<Void> claimTask(
            @RequestBody ProductionTaskClaimRequest request,
            HttpServletRequest httpRequest
    ) {
        User loginUser = userService.getLoginUser(httpRequest);

        boolean success = productionExecutionService.claimTask(
                request,
                loginUser.getId(),
                loginUser.getUserName(),
                loginUser.getDepartmentId()
        );

        if (!success) {
            return ResultUtils.error(ErrorCode.OPERATION_ERROR, "认领失败");
        }

        return ResultUtils.success(null);
    }

// ==================== 烘粉清机接口 ====================

    /**

     开始烘粉清机
     */
    @PostMapping("/tasks/{taskId}/powder-cleaning/start")
    public BaseResponse<Void> startPowderCleaning(
            @PathVariable("taskId") Long taskId,
            @RequestBody StartCleaningRequest request,
            HttpServletRequest httpRequest
    ) {
        User loginUser = userService.getLoginUser(httpRequest);
        request.setTaskId(taskId);

        boolean success = productionExecutionService.startPowderCleaning(
                request,
                loginUser.getId(),
                loginUser.getUserName()
        );

        if (!success) {
            return ResultUtils.error(ErrorCode.OPERATION_ERROR, "操作失败");
        }

        return ResultUtils.success(null);
    }

    /**

     完成烘粉清机
     */
    @PostMapping("/tasks/{taskId}/powder-cleaning/complete")
    public BaseResponse<Void> completePowderCleaning(
            @PathVariable("taskId") Long taskId,
            @RequestBody CompleteCleaningRequest request,
            HttpServletRequest httpRequest
    ) {
        User loginUser = userService.getLoginUser(httpRequest);
        request.setTaskId(taskId);

        boolean success = productionExecutionService.completePowderCleaning(
                request,
                loginUser.getId(),
                loginUser.getUserName()
        );

        if (!success) {
            return ResultUtils.error(ErrorCode.OPERATION_ERROR, "操作失败");
        }

        return ResultUtils.success(null);
    }

    /**

     获取烘粉清机记录
     */
    @GetMapping("/tasks/{taskId}/powder-cleaning/record")
    public BaseResponse<CleaningRecordVO> getCleaningRecord(@PathVariable("taskId") Long taskId) {
        CleaningRecordVO record = productionExecutionService.getCleaningRecord(taskId);
        return ResultUtils.success(record);
    }
// ==================== 生产工序接口 ====================

    /**

     开始生产流程（启动第一道工序）
     */
    @PostMapping("/tasks/{taskId}/production/start")
    public BaseResponse<Void> startProduction(
            @PathVariable("taskId") Long taskId,
            @RequestBody StartProductionFlowRequest request,
            HttpServletRequest httpRequest
    ) {
        User loginUser = userService.getLoginUser(httpRequest);
        request.setTaskId(taskId);

        boolean success = productionExecutionService.startProduction(
                request,
                loginUser.getId(),
                loginUser.getUserName()
        );

        if (!success) {
            return ResultUtils.error(ErrorCode.OPERATION_ERROR, "操作失败");
        }

        return ResultUtils.success(null);
    }

    /**

     完成工序
     */
    @PostMapping("/processes/{stepId}/complete")
    public BaseResponse<ProcessCompleteVO> completeProcess(
            @PathVariable("stepId") Long stepId,
            @RequestBody CompleteProcessRequest request,
            HttpServletRequest httpRequest
    ) {
        User loginUser = userService.getLoginUser(httpRequest);
        request.setStepId(stepId);

        ProcessCompleteVO result = productionExecutionService.completeProcess(
                request,
                loginUser.getId(),
                loginUser.getUserName()
        );

        return ResultUtils.success(result);
    }

    /**

     开始工序
     */
    @PostMapping("/processes/{stepId}/start")
    public BaseResponse<Void> startProcess(
            @PathVariable("stepId") Long stepId,
            @RequestBody StartProcessRequest request,
            HttpServletRequest httpRequest
    ) {
        User loginUser = userService.getLoginUser(httpRequest);
        request.setStepId(stepId);

        boolean success = productionExecutionService.startProcess(
                request,
                loginUser.getId(),
                loginUser.getUserName()
        );

        if (!success) {
            return ResultUtils.error(ErrorCode.OPERATION_ERROR, "操作失败");
        }

        return ResultUtils.success(null);
    }

// ==================== 辅助接口 ====================

    /**

     获取操作员列表（生产部）
     */
    @GetMapping("/operators")
    public BaseResponse<List<OperatorVO>> listOperators() {
        List<OperatorVO> operators = productionExecutionService.listOperators();
        return ResultUtils.success(operators);
    }

    /**
     * 获取烘粉清机任务统计
     *
     * @param scope 统计范围 (dept=部门统计, me=个人统计)
     * @param userId 用户ID（个人统计时使用）
     * @return 烘粉清机任务统计结果
     */
    @GetMapping("/cleaning-tasks/statistics")
    public BaseResponse<Map<String, Long>> getCleaningTaskStatistics(
            @RequestParam(name = "scope", defaultValue = "me") String scope,
            @RequestParam(name = "userId", required = false) Long userId,
            HttpServletRequest request
    ) {
        if ("dept".equalsIgnoreCase(scope)) {
            Map<String, Long> statistics = productionExecutionService.getCleaningTaskStatistics(null);
            return ResultUtils.success(statistics);
        }
        if (userId == null) {
            try {
                User loginUser = userService.getLoginUser(request);
                userId = loginUser.getId();
            } catch (Exception e) {
                log.debug("获取登录用户失败，将返回空统计", e);
                return ResultUtils.success(new java.util.HashMap<>());
            }
        }
        Map<String, Long> statistics = productionExecutionService.getCleaningTaskStatistics(userId);
        return ResultUtils.success(statistics);
    }

    /**
     * 获取生产任务统计
     *
     * @param scope 统计范围 (dept=部门统计, me=个人统计)
     * @param userId 用户ID（个人统计时使用）
     * @return 生产任务统计结果
     */
    @GetMapping("/production-tasks/statistics")
    public BaseResponse<Map<String, Long>> getProductionTaskStatistics(
            @RequestParam(name = "scope", defaultValue = "me") String scope,
            @RequestParam(name = "userId", required = false) Long userId,
            HttpServletRequest request
    ) {
        if ("dept".equalsIgnoreCase(scope)) {
            Map<String, Long> statistics = productionExecutionService.getProductionTaskStatistics(null);
            return ResultUtils.success(statistics);
        }
        if (userId == null) {
            try {
                User loginUser = userService.getLoginUser(request);
                userId = loginUser.getId();
            } catch (Exception e) {
                log.debug("获取登录用户失败，将返回空统计", e);
                return ResultUtils.success(new java.util.HashMap<>());
            }
        }
        Map<String, Long> statistics = productionExecutionService.getProductionTaskStatistics(userId);
        return ResultUtils.success(statistics);
    }

    /**
     * 获取烘粉清机任务列表
     *
     * @param status 任务状态 (PENDING, IN_PROGRESS, DONE)
     * @param current 当前页码
     * @param size 每页大小
     * @return 烘粉清机任务分页列表
     */
    @GetMapping("/cleaning-tasks")
    public BaseResponse<Page<WorkflowTaskVO>> getCleaningTasks(
            @RequestParam(name = "status", required = false) String status,
            @RequestParam(name = "current", defaultValue = "1") long current,
            @RequestParam(name = "size", defaultValue = "20") long size,
            HttpServletRequest request
    ) {
        User loginUser = userService.getLoginUser(request);
        Page<WorkflowTaskVO> page = productionExecutionService.pageCleaningTasks(
                loginUser.getId(),
                status,
                current,
                size
        );
        return ResultUtils.success(page);
    }

    /**
     * 获取生产任务列表
     *
     * @param status 任务状态 (PENDING, IN_PROGRESS, DONE)
     * @param current 当前页码
     * @param size 每页大小
     * @return 生产任务分页列表
     */
    @GetMapping("/production-tasks")
    public BaseResponse<Page<WorkflowTaskVO>> getProductionTasks(
            @RequestParam(name = "status", required = false) String status,
            @RequestParam(name = "current", defaultValue = "1") long current,
            @RequestParam(name = "size", defaultValue = "20") long size,
            HttpServletRequest request
    ) {
        User loginUser = userService.getLoginUser(request);
        Page<WorkflowTaskVO> page = productionExecutionService.pageProductionTasks(
                loginUser.getId(),
                status,
                current,
                size
        );
        return ResultUtils.success(page);
    }
    /**
     * 获取任务的生产进度（新接口，返回结构化数据）
     */
    @GetMapping("/tasks/{taskId}/progress")
    public BaseResponse<ProductionProgressVO> getTaskProgress(@PathVariable("taskId") Long taskId) {
        ProductionProgressVO progress = productionExecutionService.getTaskProgress(taskId);
        return ResultUtils.success(progress);
    }

    /**
     * 批量获取任务进度（可选）
     */
    @PostMapping("/tasks/progress/batch")
    public BaseResponse<Map<Long, ProductionProgressVO>> batchGetTaskProgress(
            @RequestBody List<Long> taskIds
    ) {
        Map<Long, ProductionProgressVO> progressMap = productionExecutionService.batchGetTaskProgress(taskIds);
        return ResultUtils.success(progressMap);
    }
}